// Generic code for setting up mtui and the UI for any command line client.

import AppElement from './ui.js'

import {Root} from 'tui-lib/ui/primitives'

import {Flushable} from 'tui-lib/util/interfaces'
import * as ansi from 'tui-lib/util/ansi'

export default async function setupClient({
  backend,
  writable,
  screenInterface,
  appConfig,
}) {
  const cleanTerminal = () => {
    writable.write(ansi.cleanCursor())
    writable.write(ansi.disableAlternateScreen())
  }

  const dirtyTerminal = () => {
    writable.write(ansi.enableAlternateScreen())
    writable.write(ansi.startTrackingMouse())
  }

  dirtyTerminal()

  const flushable = new Flushable(writable, true)
  const root = new Root(screenInterface, flushable)
  root.on('rendered', () => flushable.flush())

  const size = await screenInterface.getScreenSize()
  root.w = size.width
  root.h = size.height
  root.fixAllLayout()

  flushable.resizeScreen(size)
  flushable.write(ansi.clearScreen())
  flushable.flush()

  screenInterface.on('resize', newSize => {
    root.w = newSize.width
    root.h = newSize.height
    flushable.resizeScreen(newSize)
    root.fixAllLayout()
  })

  const appElement = new AppElement(backend, appConfig)
  root.addChild(appElement)
  root.select(appElement)

  appElement.on('quitRequested', () => {
    appElement.removeListeners()
    cleanTerminal()
  })

  appElement.on('suspendRequested', () => {
    cleanTerminal()
  })

  root.select(appElement)

  // Load up initial state
  appElement.queueListingElement.buildItems()

  return {appElement, cleanTerminal, dirtyTerminal, flushable, root}
}
